package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XinYeBangUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import java.net.URL;
import java.security.Key;
import java.util.*;

import static cn.hutool.crypto.KeyUtil.generateKey;
import static com.block.common.security.util.Des3.CIPHER_ALGORITHM;
import static org.apache.catalina.manager.Constants.CHARSET;

/**
 * 78 信业帮
 */
@Service
public class XinYeBangPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Resource
    MemberSourceInfoMapper memberSourceInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String checkUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5();
        String nameMd5 = SecureUtil.md5(memberSourceInfo.getRealname()).toUpperCase();

        Long timestamp = System.currentTimeMillis();
        Map<String, Object> signMap = new HashMap<>();
        signMap.put("action", "hitLibrary");
        signMap.put("timestamp", timestamp);
        signMap.put("mobile", mobileMd5);

        List<String> keyList = JSON.parseArray(JSON.toJSONString(signMap.keySet()), String.class);
        Collections.sort(keyList);
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : keyList) {
            stringBuilder.append(StrUtil.format("{}={}&", key, signMap.get(key)));
        }
        // TODO: 2023/11/27  secretKey：商户 API 密钥
        stringBuilder.append(StrUtil.format("secretKey={}", pushApiKeyParam.getApiKey()));
        String sign = stringBuilder.toString();
        String md5Sign = SecureUtil.md5(sign).toUpperCase();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("action", "hitLibrary");
        bizMap.put("timestamp", timestamp);
        bizMap.put("mobile", mobileMd5);
        bizMap.put("name", nameMd5);
        bizMap.put("ipaddress", memberSourceInfo.getReqIp());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("sign", md5Sign);
        bizMap.put("loanMoney", XinYeBangUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("education", XinYeBangUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("zmf", XinYeBangUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("wld", -1);
        bizMap.put("creditLimit", -1);
        bizMap.put("insurance", XinYeBangUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("isHasCar", XinYeBangUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("isHasHouse", XinYeBangUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("accumulationFund", XinYeBangUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socialSecurity", XinYeBangUtil.getSocialInsurance(memberSourceInfo.getShebao()));

        //加密
        String apics = encrypt1(pushApiKeyParam.getApiKey(), JSON.toJSONString(bizMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("apics", apics);
        paramMap.put("appkey", pushApiKeyParam.getApiCode());
        paramMap.put("version", "2.0");

        checkUrl = StrUtil.trim(checkUrl);

        log.info("【信业帮】撞库开始【checkUrl】[{}]【paramMap】{}【bizMap】{}", checkUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【信业帮】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        String transId = resultObject.getString("transId");
        Integer resultType = resultObject.getInteger("resultType");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0") && StrUtil.equals(String.valueOf(resultType), "100")) {
            //  2023/11/27   resultType:100新用户 101本渠道老用户 102非本渠道老用户 103其他用户
            String preUrl = resultObject.getString("preUrl");
            pushApiResult.setApproveUrl(preUrl);
            pushApiResult.setOutOrderNo(mobileMd5.toUpperCase());
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Long timestamp = System.currentTimeMillis();

        Map<String, Object> signMap = new HashMap<>();
        signMap.put("age", memberSourceInfo.getAge());
        signMap.put("phone", memberSourceInfo.getMobile());
        signMap.put("realName", memberSourceInfo.getRealname());
        signMap.put("sex", memberSourceInfo.getSex());

        List<String> keyList = JSON.parseArray(JSON.toJSONString(signMap.keySet()), String.class);
        Collections.sort(keyList);
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : keyList) {
            stringBuilder.append(StrUtil.format("{}={}&", key, signMap.get(key)));
        }
        stringBuilder.append(StrUtil.format("secretKey={}", pushApiKeyParam.getApiKey()));
        String sign = stringBuilder.toString();
        String md5Sign = SecureUtil.md5(sign).toUpperCase();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone",memberSourceInfo.getMobile());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("realName", memberSourceInfo.getRealname());
        bizMap.put("sign", md5Sign);
        bizMap.put("loanMoney", XinYeBangUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("city", memberSourceInfo.getCity());
//        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("education", XinYeBangUtil.getxueli(memberSourceInfo.getXueli()));

        bizMap.put("occupation", XinYeBangUtil.getjob(memberSourceInfo.getGongzuo()));
        Integer shouru = XinYeBangUtil.getShouru(memberSourceInfo.getShouru());
        bizMap.put("occupationData", XinYeBangUtil.getjobData(memberSourceInfo.getGongzuo(),shouru));

        bizMap.put("accumulationFund", XinYeBangUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socialSecurity", XinYeBangUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("creditLimit", -1);
        bizMap.put("isHasHouse", XinYeBangUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("houseData", XinYeBangUtil.getHouseData(memberSourceInfo.getHouse()));
        bizMap.put("isHasCar", XinYeBangUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("carData", XinYeBangUtil.getCarData(memberSourceInfo.getCar()));
        bizMap.put("zmf", XinYeBangUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("wld", -1);

        bizMap.put("insurance", XinYeBangUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("insuranceData", XinYeBangUtil.getbaodanData(memberSourceInfo.getBaoxian()));

        bizMap.put("creditRecord", XinYeBangUtil.getyuqi(memberSourceInfo.getYuqi()));

        bizMap.put("loanGoal",XinYeBangUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("loanTime",XinYeBangUtil.getloanTime(memberSourceInfo.getLoanTime()));

        //加密
        String apics = encrypt1(pushApiKeyParam.getApiKey(), JSON.toJSONString(bizMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("apics", apics);
        paramMap.put("appkey", pushApiKeyParam.getApiCode());
        paramMap.put("version", "2.0");

        log.info("【信业帮】导单开始【queryUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【信业帮】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        String transId = resultObject.getString("transId");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {

            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject = JSON.parseObject(paramContent);
        String phone = jsonObject.getString("phone");

        noticeParamDTO.setOutOrderNo(phone);
        noticeParamDTO.setOutFlag(true);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, phone);
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();

        Long uid = extObject.getLong("uid");

        MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectById(uid);

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String jumpUrl = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());

        jsonObject.put("code", 0);
        jsonObject.put("msg", "成功");
        jsonObject.put("redirectUrl", jumpUrl);

        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    /**
     * DES加密字符串
     *
     * @param password 加密密码，长度不能够小于8位
     * @param data     待加密字符串
     * @return 加密后内容
     */
    public static String encrypt1(String password, String data) {
        String s = SecureUtil.des(password.getBytes()).encryptBase64(data);
        return s;

    }
    public static String encrypt(String password, String data) {
        if (password == null || password.length() < 8) {
            throw new RuntimeException("加密失败，key不能小于8位");
        }
        if (data == null) {
            return null;
        }
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));
            //JDK1.8及以上可直接使用Base64，JDK1.7及以下可以使用BASE64Encoder
            //Android平台可以使用android.util.Base64
            return new String(Base64.getEncoder().encode(bytes));
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }


    public static void main(String[] args) {

        String url = "https://testqyh.qyihua.com/api/hitLibrary";

//        String body = HttpUtil.createPost(url).execute().body();
//
//        System.out.println(body);

//        URL url1 = URLUtil.url(url);
//        System.out.println(url1);


        System.out.println(isValidProtocol("https"));

    }


    private static boolean isValidProtocol(String protocol) {
        int len = protocol.length();
        if (len < 1)
            return false;
        char c = protocol.charAt(0);
        if (!Character.isLetter(c))
            return false;
        for (int i = 1; i < len; i++) {
            c = protocol.charAt(i);
            if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' &&
                    c != '-') {
                return false;
            }
        }
        return true;
    }


}
